package com.atguigu.srb.core.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;

@Configuration
public class RedisConfig {

    @Resource
    RedisTemplate redisTemplate;

    @PostConstruct
    public void init(){
        //string/list/set键和值的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //hash结构的键和值的序列化器
//        redisTemplate.setHashKeySerializer();
//        redisTemplate.setHashValueSerializer();
    }


    //配置redis缓存管理器
    @Bean
    public RedisCacheManager cacheManager(LettuceConnectionFactory factory){//之前已经引入了commons-pool2依赖 并配置了连接池参数，项目启动时会自动初始化Redis的连接工厂对象
        //1、缓存管理器的配置
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600)) //缓存过期时间
//                .disableCachingNullValues() //禁止缓存空值  缓存空值可以防止缓存穿透(一个请求查询的数据缓存没有数据库也没有)
                .serializeKeysWith(RedisSerializationContext.SerializationPair.
                        fromSerializer(new StringRedisSerializer())) //设置键的序列化器
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()));
        //2、创建缓存管理器
        RedisCacheManager cacheManager = RedisCacheManager
                .builder(factory) //设置redis连接工厂对象
                .cacheDefaults(config) //缓存管理器额外的配置
                .build(); //创建缓存管理器对象
        return cacheManager;
    }



}
